<?php

class joinPay1 {

  var $payment_conf = array();

  var $member = array();

  function __construct(){
    $payment = Model("mb_payment")->getMbPaymentOpenInfo(["payment_code" => "joinpay1"]);
    $this->paymentConf = $payment['payment_config'];
    $this->member = get_mobile_member_info();
  }

  function mobile_get_code(){

    $url = "https://www.joinpay.com/trade/uniPayApi.action";

    $orderInfo = Model()->table('order')->where([
      'order_state' => ORDER_STATE_NEW,
      'buyer_id' => $this->member["member_id"],
      'pay_sn'   => $_REQUEST['pay_sn']
    ])->find();

    $orderGoods = Model()->table("order_goods")->where([
      'buyer_id' => $this->member["member_id"],
      'order_id' => $orderInfo['order_id']
    ])->find();

    $params = array(
      "p0_Version" => "1.0",
      "p1_MerchantNo" => $this->paymentConf["merchantNo"],
      "p2_OrderNo"    => $orderInfo["pay_sn"],
      "p3_Amount"     => $orderInfo["order_amount"],
      "p4_Cur"        => 1,
      "p5_ProductName"=> $orderGoods['goods_name'],
      "p9_NotifyUrl"  => SHOP_DOMAIN . "/mobile/api/payment/joinpay1/notify_url.php",
      "q1_FrpCode"    => $_REQUEST['pay_type']
    );
    $params['hmac'] = $this->joinpay_sign($params);

    $res = $this->request($url, $params);

    return json_encode($res);
  }

  public function getNotifyInfo($payment_config){
    //将系统的控制参数置空，防止因为加密验证出错
    unset($_GET['act']);
    unset($_GET['op']);
    unset($_GET['payment_code']);

    $server_hmac = $_GET["hmac"];
    unset($_GET['hmac']);

    $merchantkey = $payment_config["merchantKey"];
    ksort($_GET);
    foreach($_GET as $key => $val){
      $_GET[$key] = urldecode($val);
    }
    $str = implode('',$_GET);
    $str .= $merchantkey;
    $client_hmac = md5($str);

    if($client_hmac === $server_hmac) {
      return array(
        //商户订单号
        'out_trade_no' => $_GET['r2_OrderNo'],
        //支付宝交易号
        'trade_no' => $_GET['r9_BankTrxNo'],
      );
    }
    return false;
  }

  private function joinpay_sign($params){
    $merchantkey = $this->paymentConf["merchantKey"];
    ksort($params);
    $str = implode('',$params);
    $str .= $merchantkey;
    return md5($str);
  }

  private function request($url, $param, $decode = true){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    if ($decode) {
      return json_decode($response,true);
    }else{
      return $response;
    }
  }

}

